package cur.nature.framework.core.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class FileUtil {

    public static boolean isFileExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    public static File createFile(String pathNameAndFileName) {
        File file = new File(pathNameAndFileName);
        try {
            //获取父目录
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            //创建文件
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            file = null;
            System.err.println("新建文件操作出错");
            e.printStackTrace();
        }
        return file;
    }

    private static int replaceFile(String source_path, String target_path) throws IOException {
        int rows = 0;
            File sourceFile = new File(source_path );
            if (!sourceFile.exists()) {
                System.out.println("读取源文件异常,跳过: " + source_path);
                return 0;
            }
            File targetFile = new File(target_path);
            if (!targetFile.exists()) {
                System.out.println("读取目标文件异常,生成: " + targetFile.getPath());
                createFile(targetFile.getPath());
            }
            // 替换文件
            Files.copy(sourceFile.toPath(), targetFile.toPath(),
                    StandardCopyOption.COPY_ATTRIBUTES,StandardCopyOption.REPLACE_EXISTING);
        return rows;
    }

    // 找出文件名称的缀
    public static String getFileSufix(String fileName) {
        if (fileName == null || fileName.isEmpty()) {return null;}
        final int lastIndex = fileName.lastIndexOf(".");
        return fileName.substring(lastIndex+1);
    }
}
